import { _GT, _ST } from '../utils/storage'
import { getLocation } from '../utils/path'

const key = 'WatchRoutePlugin-pageFromMemory'
const getMemory = () => _GT(key)
const setMemory = value => _ST(key, value)

/**
 * @method WatchRoutePlugin
 * @description watch-route的插件
 * @description 该插件提供参数 parentPage parentParams pageFrom
 * @param {Class} WatchRoute watch-route的构造函数
 * 
 */
export default class WatchRoutePlugin {
	constructor(WatchRoute, options = {}) {
		this.options = options

		this.route = new WatchRoute({ rightAway: true, ...options })

		// pageFrom 映射
		this.pageFromMemory = getMemory()
	}

	apply = stat => {
		console.log('Stat use: WatchRoutePlugin')

		// 挂载route
		stat.route = this.route

		const reg = /^https?:\/\/[^/]+/
		const getPageName = (path = '') => this.pageFromMemory[path.replace(reg, '').split('?')[0]] || '/'

		stat.listen('/', (data, params) => {
			const path = params.fullPath
			if (!this.pageFromMemory[path] && data.page) this.setMemory(path, data.page)

			const parent = this.route.parentPage

			return {
				parentPage: getPageName(parent.href || ''),
				parentParams: { ...parent.query },
			}
		})

		stat.pipe(datas => {
			const chain = this.route.getOwnChain().reverse()
			if (!chain.length) chain.unshift(getLocation().href)

			const pageFrom = chain.map(getPageName)

			// datas.forEach(data => data.pageFrom = pageFrom)
			datas.forEach(data => !data.pageFrom && (data.pageFrom = pageFrom))

			return datas
		})
	}

	// 缓存页面与名称映射
	setMemory(key, value) {
		this.pageFromMemory[key] = value

		setMemory(this.pageFromMemory)
	}
}

